package com.qmgyl.marketshop.order.controller;

import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.qmfresh.service.order.facade.dto.OrderQuery;
import com.qmgyl.marketshop.api.OrderServiceApi;
import com.qmgyl.marketshop.vo.ListWithPage;
import com.qmgyl.marketshop.vo.OrderItemResult;
import com.qmgyl.marketshop.vo.OrderListResult;
import com.qmgyl.marketshop.vo.ServiceResult;

import util.DateUtils;
import util.ExcelUtil_Extend;
import util.Page;

@Controller
@RequestMapping(value = "/shop/order")
public class OrderController {

	@Autowired
	private OrderServiceApi serviceApi;
	
	@RequestMapping(value = "/{name}", method = RequestMethod.GET)
	public String order(@PathVariable("name") String name) {
		return name;
	}

	/**
	 * 条状订单列表
	 * @param req
	 * @param res
	 * @return
	 */
	@RequestMapping(value = "list")
	public String list(HttpServletRequest req, HttpServletResponse res) {
		return "order/list";
	}

	/**
	 * 订单详情
	 * @param req
	 * @param res
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "detail")
	public String detail(HttpServletRequest req, HttpServletResponse res,
			String orderId) {
		try {
		OrderQuery orderQuery=new OrderQuery();
		orderQuery.setOrderId(new Long(orderId));
		ListWithPage<OrderListResult> result=serviceApi.getList(orderQuery);
		req.setAttribute("companyInfo", result.getListData().get(0).getCompanyInfo());
		req.setAttribute("orderMain",result.getListData().get(0).getOrderMain());
		req.setAttribute("product",result.getListData().get(0).getOrderItemResults());
		req.setAttribute("orderTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(result.getListData().get(0).getOrderMain().getcT()*1000L)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "order/detail";
	}
	
	
	/**
	 * 取消订单
	 * @param req
	 * @param res
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value = "cancelOrder")
	@ResponseBody
	public String cancelOrder(HttpServletRequest req, HttpServletResponse res,
			Long orderId) {
		OrderQuery orderQuery=new OrderQuery();
		orderQuery.setOrderId(orderId);
		String result=serviceApi.cancelOrder(orderQuery);
		return result;
		
	}


	/**
	 * 订单列表
	 * @param req
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "getList")
	@ResponseBody
	public void getList(Integer rows,Integer page,Integer status,Date s_time,Date e_time,Long order_id,Integer orderFrom,HttpServletRequest req, HttpServletResponse res)
			throws Exception {
		try {
		OrderQuery orderQuery=new OrderQuery();
		if(s_time!=null&&e_time!=null){
			orderQuery.setsTime(s_time.getTime()/1000);
			orderQuery.seteTime(e_time.getTime()/1000);
		}
		orderQuery.setPage(page);
		orderQuery.setPageNum(rows);
		if(status!=null&&status!=-2){
			List<Integer> sta=new ArrayList<Integer>();
			sta.add(status);
			orderQuery.setStatus(sta);
		}
		if(order_id!=null){
			orderQuery.setOrderId(order_id);
		}
		if(orderFrom!=null&&orderFrom!=-2){
			orderQuery.setOrderFrom(orderFrom);
		}
		ListWithPage<OrderListResult> result = serviceApi.getList(orderQuery);
		List<OrderListResult> orderListResults=result.getListData();
		List<Map<String,Object>> lis=new ArrayList<Map<String,Object>>();
		for(OrderListResult order:orderListResults){
			Map<String,Object> ma=new HashMap<String,Object>();
			List<OrderItemResult> orderItemResults=order.getOrderItemResults();
			ma.put("orderId", order.getOrderMain().getOrderId()+"");
			ma.put("coustomer", order.getCompanyInfo().getName());
			ma.put("cT",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getOrderMain().getcT()*1000L)));//js.getOrderMain().getcT()
			ma.put("status", order.getOrderMain().getStatus());
			ma.put("paymentType", order.getOrderMain().getPaymentType());
			ma.put("orderFrom", order.getOrderMain().getOrderFrom());
			ma.put("orderMark", order.getOrderMain().getOrderMark());
			ma.put("goodsAmount", order.getOrderMain().getGoodsAmount());
			ma.put("orderType",  order.getOrderMain().getOrderType());
			ma.put("receivePrice", order.getOrderMain().getReceivePrice());
			List<Map<String,Object>> orderItems=new ArrayList<Map<String,Object>>();
			for(OrderItemResult or:orderItemResults){
				Map<String,Object> m =new HashMap<String,Object>();
				m.put("image", or.getImage());
				m.put("name", or.getOrderItem().getSsuName());
				m.put("num", or.getOrderItem().getNum());
				orderItems.add(m);
			}
			ma.put("orderItemResults",orderItems);
			lis.add(ma);
		}
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("total", result.getTotalCount());
		map.put("rows", lis);
	/*	Page resu = new Page();
		resu.setResultList(lis);
		resu.setStart(1);
		resu.setTotalSize(result.getTotalCount());
		resu.setPageSize(rows);*/
		res.setContentType("application/json;charset=UTF-8");
		res.getWriter().write(JSONObject.toJSONString(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 导出订单
	 * 
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "exportOrder")
	@ResponseBody
	public String exportOrder(Integer rows,Integer page,Integer status,Date s_time,Date e_time,Long order_id,Integer orderFrom,HttpServletRequest req, HttpServletResponse res)
			throws Exception {
		// 配送数据
		String fileName = "order_" + DateUtils.getYYYY_MM_DD() + ".xls";
		List<List<String>> dataList = new ArrayList<List<String>>();
		OrderQuery orderQuery=new OrderQuery();
		if(s_time!=null&&e_time!=null){
			orderQuery.setsTime(s_time.getTime()/1000);
			orderQuery.seteTime(e_time.getTime()/1000);
		}
		if(status!=null&&status.intValue()!=-2){
			List<Integer> sta=new ArrayList<Integer>();
			sta.add(status);
			orderQuery.setStatus(sta);
		}
		if(order_id!=null){
			orderQuery.setOrderId(order_id);
		}
		if(orderFrom!=null&&orderFrom!=-2){
			orderQuery.setOrderFrom(orderFrom);
		}
		ListWithPage<OrderListResult> result = serviceApi.getList(orderQuery);
		List<OrderListResult> orderListResults=result.getListData();
		int i=0;
		for(OrderListResult orderListResult:orderListResults){
			List<OrderItemResult> orderItemResults=orderListResult.getOrderItemResults();
			for(OrderItemResult order:orderItemResults){
				i++;
				List<String> rowList = new ArrayList<String>();
				rowList.add(i+"");
				rowList.add(orderListResult.getOrderMain().getOrderId()+"");
				rowList.add(order.getOrderItem().getSkuName()+"");
				rowList.add(order.getOrderItem().getSkuFormat()+"");
				rowList.add(order.getOrderItem().getNum()+"");
				rowList.add(orderListResult.getCompanyInfo().getName()+"");
				rowList.add(orderListResult.getCompanyInfo().getPhone()+"");
				rowList.add(orderListResult.getCompanyInfo().getAddress()+"");
				rowList.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(orderListResult.getOrderMain().getcT()*1000L)));
				rowList.add(orderListResult.getOrderMain().getOrderType()+"");
				rowList.add(orderListResult.getOrderMain().getOrderFrom()+"");
				rowList.add(orderListResult.getOrderMain().getRemark()+"");
				rowList.add(orderListResult.getOrderMain().getGoodsAmount()+"");
				rowList.add(orderListResult.getOrderMain().getReceivePrice()+"");
				dataList.add(rowList);
			}
		}
		String[] head = {"序号","订单ID", "商品名称","商品规格","商品数量","收货人","收货人电话","地址","下单日期","支付方式", "订单来源", "订单备注","订单金额","实收金额"};
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("订单");
		sheet.setColumnWidth(0, 2000);
		sheet.setColumnWidth(1, 8000);
		sheet.setColumnWidth(2, 8000);
		sheet.setColumnWidth(7, 15000);
		sheet.setColumnWidth(8, 10000);
		ExcelUtil_Extend.createExcelMerge(workbook, sheet, "订单", head,
				dataList, false, null, null, null, null);
		ExcelUtil_Extend.mergedRegion(sheet, 0, 1, sheet.getLastRowNum(),
				workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet, 1, 1, sheet.getLastRowNum(),
				workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet, 5, 1, sheet.getLastRowNum(),
				workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet, 7, 1, sheet.getLastRowNum(),
				workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet, 8, 1, sheet.getLastRowNum(),
				workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet, 9, 1, sheet.getLastRowNum(),
				workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet, 10, 1, sheet.getLastRowNum(),
				workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet,11, 1, sheet.getLastRowNum(),
				workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet,13,1, sheet.getLastRowNum(),
				workbook, new Integer[] { 0 });
		ExcelUtil_Extend.mergedRegion(sheet,12,1, sheet.getLastRowNum(),
				workbook, new Integer[] { 0 });

		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		// 将excel写入流
		workbook.write(byteArrayOutputStream);
		ExcelUtil_Extend.exportExelMerge(res, byteArrayOutputStream, fileName);

		return fileName;

	}
	
	
	/**
	 * 订单列表接口
	 * @param req
	 * @param res
	 * @param page
	 * @param pageSize
	 * @throws Exception
	 */
	@RequestMapping(value = "listOrder")
	@ResponseBody
	public void listOrder(HttpServletRequest req, HttpServletResponse res,String page,String pageSize)
			throws Exception {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < new Integer(pageSize).intValue(); i++) {
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("order_id","20180612000"+i);//id
			data.put("order_mark", "9.30前送到");//备注
			data.put("goods_amount", "21"+i); //商品总价格
			data.put("phone", "1379898243"+i);//配送电话
			data.put("address", "水西门大街"+i+"号");//配送地址
			data.put("consignee", "张三");//收货人姓名
			data.put("name", "黄焖鸡米饭");//下单人名字
			list.add(data);
		}
		ListWithPage<Map<String, Object>> pa =new ListWithPage<Map<String, Object>>();
		pa.setListData(list);
		pa.setTotalCount(10);
		String json =com.alibaba.fastjson.JSONObject.toJSONString(pa);
		res.setContentType("text/html;charset=UTF-8");
		res.getWriter().write(json);
	}

	/**
	 * 订单详情接口
	 * @param req
	 * @param res
	 * @param order_id
	 * @throws Exception
	 */
	@RequestMapping(value = "orderDetail")
	@ResponseBody
	public void orderDetail(HttpServletRequest req, HttpServletResponse res,String order_id)
			throws Exception {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("productName", "土豆1kg");//商品名称
			data.put("productFormat","1斤/袋");//商品规格
			data.put("price","1.0");//单价
			data.put("amount", 2);//数量
			data.put("image","http://pic.qiantucdn.com/58pic/15/42/64/49K58PICZNx_1024.jpg");//数量
			Map<String, Object> data2 = new HashMap<String, Object>();
			data2.put("productName", "白菜1kg");//商品名称
			data2.put("productFormat","1斤/袋");//商品规格
			data2.put("price","3.0");//单价
			data2.put("amount", 4);//数量
			data2.put("image","https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1524889058451&di=947b6efaeab223db85549ad5bfeb79cf&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F0b46f21fbe096b63e5f2429906338744eaf8ac0b.jpg");//数量
			list.add(data2);
			list.add(data);
		ServiceResult<List<Map<String, Object>>> result=new ServiceResult<List<Map<String,Object>>>();
		result.setBody(list);
		result.setMessage("sucess");
		result.setSuccess(true);
		String json =com.alibaba.fastjson.JSONObject.toJSONString(result);
		res.setContentType("text/html;charset=UTF-8");
		res.getWriter().write(json);
	}

	/**
	 * 日期格式数据绑定
	 * 
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		sf.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(sf, true));
	}
}